package process;

import java.util.ArrayList;
import java.util.List;

import javafx.application.Platform;
import memory.*;

public class Process {
	private List<Myinstuction> instructions = new ArrayList<Myinstuction>();//储存指令
	
	private static void decodeError(int i) {
//		System.out.println("编译错误 在第"+i+"个字符处");	
		ProcessController.getProcessController().outPut("编译错误 在第"+i+"个字符处\n");
		
	}
	
	
	public Process() {					//不带参数的构造方法，构造闲逛进程用
		super();
		for(int i=0;i<5;i++)
		instructions.add(new HangOutInstruction());//生成5条闲逛命令
		instructions.add(new EndInstruction());
	}
	public Process(String str) {
		getInstructions(str);
	}
	
	private void getInstructions(String str) {
		for(int i=0;i<str.length();i++) {
			switch(str.charAt(i)){
			case 'x' : 
				if(str.charAt(i+1)=='=') {//赋值操作
					if(str.charAt(i+2)<='9'&&str.charAt(i+2)>='0') {
						int val = str.charAt(i+2)-'0';
						i+=2;											//游标右进2位
						if(str.charAt(i+1)<='9'&&str.charAt(i+1)>='0') {//是二位数
							val = val*10 + str.charAt(i+1)-'0';
							i++;										//游标右进1位
						}
						instructions.add(new AssignmentInstruction(val));
					}
					else {
						decodeError(i);
					}
				}
				else if(str.charAt(i+1)=='+'&& str.charAt(i+2)=='+') {//自加操作
					instructions.add(new PlusInstruction());
					i+=2;
				}
				else if(str.charAt(i+1)=='-'&& str.charAt(i+2)=='-') {//自减操作
					instructions.add(new SubtractInstruction());
					i+=2;
				}else {
					decodeError(i);
				}
				break;	
			case '!' :
				if(str.charAt(i+1)=='A')instructions.add(new DeviceInstruction('A', CPU.getCpu().getPcb().getPid(), str.charAt(i+2)-'0'));
				else if(str.charAt(i+1)=='B')instructions.add(new DeviceInstruction('B', CPU.getCpu().getPcb().getPid(), str.charAt(i+2)-'0'));
				else if(str.charAt(i+1)=='B')instructions.add(new DeviceInstruction('B', CPU.getCpu().getPcb().getPid(), str.charAt(i+2)-'0'));
				else {
					decodeError(i);
				}
				i+=2;
				break;
			case 'e' :
				if(str.charAt(i+1)=='n'&&str.charAt(i+2)=='d') {
					instructions.add(new EndInstruction());
					i+=2;
				}else {
					decodeError(i);
				}
				break;
			default:
				break;
			}
		}
	}
	
	//执行进程一条指令
	public void excuteInstruction(int pc) {
		instructions.get(pc).run();
	}
	
	//闲逛进程
	private static Process hangOutProcess;
	public static Process getHangOutProcess() {
		if(hangOutProcess==null) {
			hangOutProcess = new Process();
		}
		return hangOutProcess;
	}
	
}
